#-*-coding:utf-8-*-

from concurrent.futures import ThreadPoolExecutor
import requests
import re,json
import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

pool = ThreadPoolExecutor(max_workers=3)

HOSTNAME = "rm-bp19zw8bq66jagg6o.mysql.rds.aliyuncs.com"
PORT = "3306"
DATABASE = "uat_price_prediction"
USERNAME = "uat_price_rw"
PASSWORD = "6TtydXAj3qp7eOz1cBtb"

DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset=utf8". \
    format(username=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, db=DATABASE)

engine = create_engine(DB_URI)
Session = sessionmaker(bind=engine)
session = Session()
sql='''
select count(1) from price_prediction a
-- select * from price_prediction a
inner join dim_product_tmp dp
on a.product_brand_name=dp.product_brand_name
and a.product_category_id=5
and dp.product_category_id=5
where dp.product_brand_id in (184,9,484,272,52) and a.product_category_id=5
'''

#where dp.product_brand_id in (184,9,484,272,52) and a.product_category_id=5
#category_id in (22,23,24,25,26,77,81)

# sql='''
# select count(1) from price_prediction a
# -- select * from price_prediction a
# inner join dim_product_tmp dp
# on a.product_brand_name=dp.product_brand_name
# and a.product_category_id in (23)
# and dp.product_category_id in (23)
# '''
cur = session.execute(sql)
data = cur.fetchall()
ttl=data[0][0]
print(datetime.datetime.now(), '-ttl_count-',ttl)

sql='''
select
dp.product_brand_id as brand_id,
a.product_category_id as category,
a.product_key as product,
a.product_sku_key as sku,
a.product_level_key as level
from price_prediction a
-- select * from price_prediction a
inner join dim_product_tmp dp
on a.product_brand_name=dp.product_brand_name
and a.product_category_id=5
and dp.product_category_id=5
where dp.product_brand_id in (184,9,484,272,52) and a.product_category_id=5

'''
#where dp.product_brand_id in (184,9,484,272,52) and a.product_category_id=5
#category_id in (22,23,24,25,26,77,81)


# sql='''
# select
# dp.product_brand_id as brand_id,
# a.product_category_id as category,
# a.product_key as product,
# a.product_sku_key as sku,
# a.product_level_key as level
# from price_prediction a
# -- select * from price_prediction a
# inner join dim_product_tmp dp
# on a.product_brand_name=dp.product_brand_name
# and a.product_category_id in (23)
# and dp.product_category_id in (23)
#
# '''
cur = session.execute(sql)
data = cur.fetchall()
# print(data)
session.close()

def list_of_groups(init_list, children_list_len):
    list_of_groups = zip(*(iter(init_list),) *children_list_len)
    end_list = [list(i) for i in list_of_groups]
    count = len(init_list) % children_list_len
    end_list.append(init_list[-count:]) if count !=0 else end_list
    return end_list


class Thread_test():

    def get_page(self,url,json_data,line):
        # print('line:%s GET start ...' % line)
        print(datetime.datetime.now(), '-start_line-',line,'-len-',len(json_data.get('data',[])))
        index_res = requests.post(url,json=json_data,headers={'Content-Type':'application/json','version':'1.1.0'})
        return index_res.text,line

    def parse_index(self,index_page):
        # 拿到主页的返回结果
        res,line = index_page.result()
        # print(datetime.datetime.now(), '-end_line-', line, '-result-', res)
        try:
            res=json.loads(res)
            price_ok_num = 0
            price_none_num = 0
            for i in res:
                if i['price'] == None:
                    price_none_num += 1
                else:
                    price_ok_num += 1
            print(datetime.datetime.now(), '-end_line-', line, '-ok_len-', price_ok_num,'-none_len-', price_none_num)

        except:
            print(datetime.datetime.now(), '-end_line-', line, '-error-',res)

        # pool.submit(get_page, detail_url).add_done_callback(parse_detail)
        # pool.submit(save_video, video_urls)



if __name__ == '__main__':
    obj=Thread_test()
    # base_url = 'http://192.168.103.170:6668/price/predict'
    # base_url = 'http://abprice-api-uat.aihuishou.com/api/c/jd/price/predict/batch'
    base_url = 'http://abprice-api-uat.aihuishou.com/api/c/price/predict/batch'
    print(datetime.datetime.now(),'-thread_start')
    # for line in range(20):
    #     print('第几页{}'.format(line))
    #     json_data={
    #
    #                 "token": "48ede0718ba6c1eebf8b8c684778d266",
    #                 "data": [
    #                     {
    #                         "brand": 9,
    #                         "category": 5,
    #                         "product": 26538,
    #                         "sku": 42251,
    #                         "level": 3416
    #                     },
    #                     {
    #                         "brand": 9,
    #                         "category": 5,
    #                         "product": 26538,
    #                         "sku": 42252,
    #                         "level": 3416
    #                     }
    #                 ]
    #             }
    #     index_url = base_url
    #     # pool.submit(obj.get_page, index_url,json_data,line).add_done_callback(obj.parse_index)
    i=1
    code_lists = list_of_groups(data, 10)
    # for code_list in code_lists:
    for i in range(len(code_lists)):
        res_item = []
        for item in code_lists[i]:
            one = {
                "brand": item[0],
                "category": item[1],
                "product": item[2],
                "sku": item[3],
                "level": item[4]
            }
            res_item.append(one)
        # print(i,res_item)
        json_data = {
                    "token": "48ede0718ba6c1eebf8b8c684778d266",
                    "data": res_item
                        }
        # print(json_data)
        i+=1
        # if i>10:
        #     break
        index_url = base_url
        pool.submit(obj.get_page, index_url,json_data,i).add_done_callback(obj.parse_index)
    print(datetime.datetime.now(), '-thread_end')